package tum0r.utils;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.LinkedList;

/**
 * 工程: XJSON<br>
 * 包: tum0r.utils<br>
 * 创建者: tum0r<br>
 * 创建时间: 2020/9/15 14:14<br>
 * <br>
 */
public class GetFields {

    public LinkedList<Field> getFields(Object o) {
        if (o == null) {
            o = new Object();
        }
        return getFields(o.getClass());
    }

    public LinkedList<Field> getFields(Class<?> c) {
        LinkedList<Field> result = new LinkedList<>();
        if (c != null) {
            Field[] fields = c.getFields();
            for (Field field : fields) {
                field.setAccessible(true);
                result.add(field);
            }
        }
        return result;
    }

    public Object getFieldValue(Object data, Field field) {
        Object result = null;
        try {
            if (data != null && field != null) {
                result = field.get(data);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return result;
    }

    public LinkedHashMap<Field, Object> getFieldsValue(Object data, LinkedList<Field> fields) {
        LinkedHashMap<Field, Object> result = new LinkedHashMap<>();
        if (data != null && fields != null) {
            result = getFieldsValue(data, fields.toArray(new Field[0]));
        }
        return result;
    }

    public LinkedHashMap<Field, Object> getFieldsValue(Object data, Field[] fields) {
        LinkedHashMap<Field, Object> result = new LinkedHashMap<>();
        if (data != null && fields != null) {
            for (Field field : fields) {
                result.put(field, getFieldValue(data, field));
            }
        }
        return result;
    }
}
